#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
订单管理API路由
"""

from flask import Blueprint, request, jsonify
from models.order import Order
from models.user import User
from models.table import BilliardTable
from database import db
from utils.decorators import admin_required, token_required
from datetime import datetime, timedelta
from sqlalchemy import or_, and_

order_bp = Blueprint('order', __name__)

@order_bp.route('/', methods=['GET'])
@admin_required
def get_orders(admin):
    """获取订单列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        status = request.args.get('status', '')
        order_type = request.args.get('order_type', '')
        payment_status = request.args.get('payment_status', '')
        start_date = request.args.get('start_date', '')
        end_date = request.args.get('end_date', '')
        
        # 构建查询
        query = Order.query
        
        if search:
            query = query.join(User).filter(or_(
                Order.order_no.like(f'%{search}%'),
                Order.title.like(f'%{search}%'),
                User.nickname.like(f'%{search}%')
            ))
        
        if status:
            query = query.filter(Order.status == status)
        
        if order_type:
            query = query.filter(Order.order_type == order_type)
        
        if payment_status:
            query = query.filter(Order.payment_status == payment_status)
        
        if start_date:
            start = datetime.strptime(start_date, '%Y-%m-%d')
            query = query.filter(Order.created_at >= start)
        
        if end_date:
            end = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
            query = query.filter(Order.created_at < end)
        
        # 分页查询
        pagination = query.order_by(Order.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        orders = pagination.items
        
        return jsonify({
            'success': True,
            'data': {
                'orders': [order.to_dict() for order in orders],
                'pagination': {
                    'page': page,
                    'pages': pagination.pages,
                    'per_page': per_page,
                    'total': pagination.total,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取订单列表失败: {str(e)}'}), 500

@order_bp.route('/<int:order_id>', methods=['GET'])
@admin_required
def get_order(admin, order_id):
    """获取订单详情"""
    try:
        order = Order.query.get(order_id)
        if not order:
            return jsonify({'success': False, 'message': '订单不存在'}), 404
        
        return jsonify({
            'success': True,
            'data': order.to_dict()
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取订单详情失败: {str(e)}'}), 500

@order_bp.route('/create', methods=['POST'])
def create_order():
    """创建订单（小程序端调用）"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['user_id', 'order_type', 'title', 'final_amount']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'message': f'缺少必要字段: {field}'}), 400
        
        # 创建订单
        order = Order(
            user_id=data['user_id'],
            table_id=data.get('table_id'),
            order_type=data['order_type'],
            title=data['title'],
            description=data.get('description'),
            original_amount=data.get('original_amount', data['final_amount']),
            discount_amount=data.get('discount_amount', 0),
            final_amount=data['final_amount'],
            start_time=datetime.fromisoformat(data['start_time']) if data.get('start_time') else None,
            end_time=datetime.fromisoformat(data['end_time']) if data.get('end_time') else None,
            duration_minutes=data.get('duration_minutes'),
            hourly_rate=data.get('hourly_rate'),
            remark=data.get('remark')
        )
        
        db.session.add(order)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '订单创建成功',
            'data': order.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'创建订单失败: {str(e)}'}), 500

@order_bp.route('/<int:order_id>/status', methods=['PUT'])
@admin_required
def update_order_status(admin, order_id):
    """更新订单状态"""
    try:
        order = Order.query.get(order_id)
        if not order:
            return jsonify({'success': False, 'message': '订单不存在'}), 404
        
        data = request.get_json()
        new_status = data.get('status')
        remark = data.get('remark', '')
        
        if not new_status:
            return jsonify({'success': False, 'message': '缺少状态参数'}), 400
        
        old_status = order.status
        order.status = new_status
        order.updated_at = datetime.now()
        
        if remark:
            order.remark = remark
        
        # 如果是台桌订单，更新台桌状态
        if order.order_type == 'table_rental' and order.table_id:
            table = BilliardTable.query.get(order.table_id)
            if table:
                if new_status == 'in_progress':
                    table.status = 'occupied'
                    table.current_user_id = order.user_id
                    table.current_order_id = order.id
                    table.occupied_since = order.start_time or datetime.now()
                elif new_status in ['completed', 'cancelled']:
                    table.status = 'available'
                    table.current_user_id = None
                    table.current_order_id = None
                    table.occupied_since = None
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '订单状态更新成功',
            'data': {
                'order_id': order_id,
                'old_status': old_status,
                'new_status': new_status
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'更新订单状态失败: {str(e)}'}), 500

@order_bp.route('/statistics', methods=['GET'])
@admin_required
def get_order_statistics(admin):
    """获取订单统计信息"""
    try:
        # 基础统计
        total_orders = Order.query.count()
        paid_orders = Order.query.filter(Order.payment_status == 'paid').count()
        pending_orders = Order.query.filter(Order.payment_status == 'pending').count()
        
        # 今日订单
        today = datetime.now().date()
        today_orders = Order.query.filter(
            Order.created_at >= today,
            Order.created_at < today + timedelta(days=1)
        ).count()
        
        # 今日营收
        today_revenue = db.session.query(db.func.sum(Order.final_amount)).filter(
            Order.created_at >= today,
            Order.created_at < today + timedelta(days=1),
            Order.payment_status == 'paid'
        ).scalar() or 0
        
        # 本月营收
        month_start = today.replace(day=1)
        month_revenue = db.session.query(db.func.sum(Order.final_amount)).filter(
            Order.created_at >= month_start,
            Order.payment_status == 'paid'
        ).scalar() or 0
        
        # 订单类型统计
        order_types = db.session.query(
            Order.order_type, 
            db.func.count(Order.id)
        ).group_by(Order.order_type).all()
        
        return jsonify({
            'success': True,
            'data': {
                'total_orders': total_orders,
                'paid_orders': paid_orders,
                'pending_orders': pending_orders,
                'today_orders': today_orders,
                'today_revenue': float(today_revenue),
                'month_revenue': float(month_revenue),
                'order_types': [{'type': t[0], 'count': t[1]} for t in order_types],
                'paid_rate': round(paid_orders / total_orders * 100, 2) if total_orders > 0 else 0
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取统计信息失败: {str(e)}'}), 500